package cn.flying.base.security.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import cn.flying.base.common.enums.RtCodeEnum;
import cn.flying.base.common.vo.Rt;
import com.alibaba.fastjson2.JSON;

/**
 * @description: 认证过的用户访问无权限资源时的异常处理器
 * @author: lvyong
 * @date: 2023年05月25日 19:32
 * @version: 1.0
 */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException {
        logger.error("访问拒绝", exception);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        //登录成功返回用户信息
        out.write(JSON.toJSONString(Rt.error(RtCodeEnum.R10015)));
        out.flush();
        out.close();
    }
}